<?php

/**
 * @time: 2021-10-20 AM
 */

namespace backend\utils;

use backend\models\file\AttExtend;
use Faker\Provider\Uuid;
use Yii;
use yii\helpers\Url;
use yii\web\Response;
use yii\web\UploadedFile;


class NBFile
{
    // 最大可上传大小 M
    const MAX_SIZE = 50;

    public static $can_upload_file_type = [
        'pdf',
        'xls',
        'xlsx',
        'doc',
        'docx',
        'zip',
        'rar'
    ];


    /**
     * @desc 上传文件的方法
     * @return array
     * @Date: 2024/11/1
     */
    public static function file_upload($file_name = 'file', $max_size = false, $can_upload_file_type = false)
    {
        $sql_url = "/files/up_file/" . date('Ymd') . "/";
        $upload_url = AppUtil::get_web_path() . $sql_url;

        $max_size = $max_size ? $max_size : self::MAX_SIZE;
        $can_upload_file_type = $can_upload_file_type ? $can_upload_file_type : self::$can_upload_file_type;
        $file = UploadedFile::getInstanceByName($file_name);

        if (!$file) {
            return [0, '请选择要上传文件', ""];
        }
        if ($file->size > (1024 * 1024 * $max_size)) {
            return [0, '请上传' . $max_size . 'MB以内的文件', ""];
        }
        if (!in_array($file->extension, $can_upload_file_type)) {
            return [0, '请上传' . implode(",", $can_upload_file_type) . '文件', ""];
        }

        if (!is_dir($upload_url)) {
            mkdir($upload_url, 0777, true);
        }

        if ($file) {
            $uid = uniqid(time(), true);
            $fileName = $uid . '.' . $file->extension;
            $filePath = $upload_url . $fileName;
            if ($file->saveAs($filePath)) {
                $path = $sql_url . $fileName;
                return [200, '上传成功', [
                    [
                        'uuid' => Uuid::uuid(),
                        'file_name' => $file->name,
                        'att_name' => $fileName,
                        'att_type' => $file->extension,
                        'att_size' => $file->size,
                        'att_position' => $path,
                        'submit_time' => date('Y-m-d H:i:s'),
                        'viewUrl' => self::file_view($path),
                        'downloadUrl' => Url::toRoute(['pub/download-file', 'path' => $path, 'name' => $file->name]),
                    ],
                ]];
            }
        }
        return [0, '上传失败', ""];
    }

    public static function file_view($path)
    {
        return Yii::$app->request->baseUrl . $path;
    }


    /*
     * 创建文件表
     */
    public static function add_att_extend($attachment_id, $file, $table_field = '-')
    {
        $code = 200;
        $attE = new AttExtend();
        $attE->uuid = Uuid::uuid();
        $attE->main_att_id = $attachment_id;
        $attE->att_name = $file['att_name'];
        $attE->att_position = $file['att_position'];
        $attE->att_size = (string)$file['att_size'];
        $attE->att_type = $file['att_type'];
        $attE->file_name = $file['file_name'];
        $attE->submit_time = $file['submit_time'];
        $attE->table_field = $table_field;
        $attE->status = 1;
        $res = $attE->save();
        if ($res == false) {
            $code = 0;
        }
        return [$code, AppUtil::get_error_msg($attE)];
    }

    /*
     * 更新文件表
     */
    public static function update_att_extend($attachment_id, $file, $uuid, $new_uuid)
    {
        $ae = AttExtend::findOne($uuid);

        $code = 200;
        $attE = new AttExtend();
        $attE->uuid = $new_uuid;
        $attE->main_att_id = $attachment_id;
        $attE->att_name = $file['att_name'];
        $attE->att_position = $file['att_position'];
        $attE->att_size = (string)$file['att_size'];
        $attE->att_type = $file['att_type'];
        $attE->file_name = $file['file_name'];
        $attE->submit_time = $ae->submit_time;
        $attE->update_time = $file['submit_time'];
        $attE->former_uuid = $uuid;
        $attE->status = 1;
        $query = $attE->save();

        $ae->status = 2;
        $query2 = $ae->save();

        if ($query == false || $query2 == false) {
            $code = 0;
            return self::return_api($code, '', [], false);
        } else {
            return self::return_api($code, '', ['uuid' => $attE->uuid], false);
        }
    }

    /*
     * 数据入库
     */
    public static function db_save($attachment_id, $attachments, $delAttachmentIds)
    {
        //附件
        foreach ($attachments as $attachment) {
            if (!$attachment['main_att_id']) {
                $re_arr = self::add_att_extend($attachment_id, $attachment);
                if (!$re_arr['code']) {
                    return self::return_api(0, '文件保存失败', [], false);
                }
            }
        }
        //附件--删除
        if ($delAttachmentIds) {
            $delAttachmentIds = trim($delAttachmentIds, ",");;
            $res = AttExtend::updateAll([
                'status' => 2,
            ], [
                'uuid' => explode(',', $delAttachmentIds),
                'status' => 1,
            ]);
            if ($res === false) {
                return self::return_api(0, '删除文件失败', [], false);
            }
        }
        return self::return_api(200, '保存成功', [], false);
    }

    /*
     * 删除文件表
     */
    public static function del_att_extend($uuid)
    {
        $res = AttExtend::updateAll([
            'status' => 2,
        ], [
            'uuid' => $uuid,
            'status' => 1,
        ]);
        if ($res === false) {
            return self::return_api(0, '删除文件失败', [], false);
        }

        return self::return_api(200, '删除成功', [], false);
    }

    public static function return_api($code, $msg = '', $data = [], $is_json = true)
    {
        if ($is_json) {
            Yii::$app->response->format = Response::FORMAT_JSON;
        }
        return [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
            'time' => date('Y-m-d H:i:s'),
        ];
    }


}
